import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Button, Input, message, Icon, Form, Select, AutoComplete } from 'antd';
import { routerRedux } from 'dva/router';
import styles from './index.less';

const EditModal = React.lazy(() => import('./editModal'));
const FieldTable = React.lazy(() => import('./fieldTable'));
const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;
let  responseFieldArr = []; let requestFieldArr = [];
const formItemLayout = {
  labelCol: {
    xs: { span: 1 },
    sm: { span: 2  },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};
@connect(({ customApi, loading }) => ({
  customApi,
  loading: loading.effects['customApi/fetchApiDetailById'],
}))

class CustomApi extends Component {
  constructor(props) {
    super(props);
    this.state = {
      requestField: [],
      responseField: [],
      fieldType: null,
      apiId: null,
      name: null,
      url: null,
      errorMessage: null,
      method: "POST",
      isUsed: false,
      fieldObj:{}
    };
    this.requestFieldColumns = [
      {
        key: 'name',
        align: 'left',
        title: '字段业务名',
        dataIndex: 'name',
      },
      {
        key: 'id',
        align: 'left',
        title: '字段名',
        dataIndex: 'id',
      },
      {
        key: 'fieldType',
        align: 'left',
        title: '类型',
        dataIndex: 'fieldType',
      },
      {
        title: '操作',
        align: 'left',
        render: (text, row) => {
          return <div>
            <Button htmlType='button' size='small' className={styles.processBtn} onClick={() => this.editFieldById(row,'requestField')}>
              <FormattedMessage
                id="app.processTemplate.btn-edit"
              />
            </Button>
            <Button type="danger" htmlType='button' size='small' className={styles.processBtn} onClick={() => this.delFieldById(row,'requestField')}>
              <FormattedMessage
                id="app.processTemplate.btn-del"
              />
            </Button>
          </div>;
        },
        width: '180px',
      },
    ];
    this.responseFieldColumns = [
      {
        key: 'name',
        align: 'left',
        title: '字段业务名',
        dataIndex: 'name',
      },
      {
        key: 'id',
        align: 'left',
        title: '字段名',
        dataIndex: 'id',
      },
      {
        key: 'fieldType',
        align: 'left',
        title: '类型',
        dataIndex: 'fieldType',
      },
      {
        title: '操作',
        align: 'left',
        render: (text, row) => {
          return <div>
            <Button htmlType='button' size='small' className={styles.processBtn} onClick={() => this.editFieldById(row,'responseField')}>
              <FormattedMessage
                id="app.processTemplate.btn-edit"
              />
            </Button>
            <Button type="danger" htmlType='button' size='small' className={styles.processBtn} onClick={() => this.delFieldById(row,'responseField')}>
              <FormattedMessage
                id="app.processTemplate.btn-del"
              />
            </Button>
          </div>;
        },
        width: '180px',
      },
    ];
  }

  componentDidMount() {
    if( this.props.location.state.apiId){
      this.setState({
        apiId: this.props.location.state.apiId
      },()=>{
        this.fetchApiDetailById(this.state.apiId)
      })
    }requestFieldArr = [];
     responseFieldArr = [];
  }

  componentWillUnmount(){
    this.props.form.resetFields()
  }

  saveApi =(e)=>{
    const { dispatch } = this.props;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      let obj = values;
      obj['requestFields'] = this.state.requestField;
      obj['responseFields'] = this.state.responseField;
      obj['apiId'] = this.state.apiId;
      if (!err) {
        dispatch({
          type: 'customApi/add',
          payload: obj,
          callback:(res)=>{
            console.log(res);
            this.setState({
              fieldObj: obj
            },()=>{
              let ret = JSON.stringify(res);
              if(ret === "{}"){
                return ""
              }else{
                if(res.msg){
                  message.info(res.msg);
                }else{
                  this.setState({
                    apiId:res.apiId
                  },()=>{
                    message.info('保存成功');
                  })
                }
              }
            })
          }
        });
      }
    });

  };

  pushRequestField = (val, type, method) =>{
    console.log(val,type,method)
    if(!this.ArrayDetection(val)){
      return message.error('该字段名已存在，请替换再试')
    }
    if(type ==='requestField'){
      if(method === 'edit'){
        this.dataFix(val);
      }
      requestFieldArr.push(val);
      this.setState({
          requestField: requestFieldArr
      },()=>{
        console.log(this.state)
      })
    }else{
      if(method === 'edit'){
        this.dataFix(val);
      }
      responseFieldArr.push(val);
      this.setState({
          responseField: responseFieldArr
      },()=>{
        console.log(this.state)
      })
    }
  };

  addField(type){
    this.setState({
      fieldType: type
    },()=>{
      console.log(this.EditModal);
      this.EditModal.showModal(type)
    })
  };

  checkUrl(rule, value, callback) {
    if (value.indexOf('http') === -1) {
      callback('接口请求地址格式不正确');
    }else{
      callback()
    }
  };

  dataFix(row){
    const that = this;
    let type = row.type;
    let arr = that.state[type];
    arr.splice(arr.findIndex(v => v.id === row.id),1);
  }

  ArrayDetection(row){
    const that = this;
    let type = row.type;
    let arr = that.state[type];
    let result = arr.find(item => {
      return item.id == row.id;
    });
    return !result;
  }


  delFieldById(row,requestMethod){
    const  that = this;
    let type = requestMethod;
    let arr = that.state[type];
    arr.splice(arr.findIndex(v => v.id === row.id),1);
    that.setState({
      [type]: arr
    },()=>{
      console.log(this.state)
    })
  };

  editFieldById(row,requestMethod){
    const  that = this;
    let type = requestMethod;
    console.log(row);
    this.setState({
      fieldType: type
    },()=>{
      this.EditModal.showModal(type,row,'edit')
    })
  };

  fetchApiDetailById(id){
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/fetchApiDetailById',
        payload: {apiId:id},
        callback: (res)=>{
          console.log(res)
          requestFieldArr= res.requestFields;
          responseFieldArr= res.responseFields;
          this.setState({
            name: res.name,
            url: res.url,
            method: res.method,
            isUsed: res.isUsed,
            errorMessage: res.errorMessage,
            requestField:  res.requestFields,
            responseField: res.responseFields,
            fieldObj:res
          },()=>{
            console.log(this.state)
          })

        }
      });
    });
  }

  testApi(obj){
    const { dispatch } = this.props;
    console.log(obj);
    if(JSON.stringify(obj) === '{}'){
      return message.error('请先保存后，再开始测试')
    }
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'customApi/test',
        payload: {api: obj},
      });
    });
  }

  backList(){
    const { dispatch } = this.props;
    dispatch(routerRedux.push('/basic/customApi'));
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const {isUsed} = this.state;
      // @ts-ignore
    // @ts-ignore
    return (
        <Suspense fallback={<PageLoading />}>
            <Row className={styles.colorBackground}>
              <Col style={{ padding: 10 }} xs={5}>
                <div className={styles.title}>
                  <FormattedMessage
                    id="app.customApi.title-edit"
                  />
                </div>
              </Col>

              <div style={{float:'right',paddingTop:16,paddingRight:20,color:'rgb(21,144,255)',cursor: 'pointer'}} onClick={()=>this.backList()}>
                <Icon type="bars" style={{marginRight: 5}} />
                <FormattedMessage
                  id="app.customApi.backList"
                />
              </div>
            </Row>
            <Card bordered={false}  className={styles.listContent}>
              <Form {...formItemLayout} onSubmit={this.saveApi}>
                <Form.Item
                  label={<FormattedMessage id="app.customApi.apiName" />}
                  hasFeedback
                >

                  {getFieldDecorator('name', {
                    rules: [{
                      required: true, message: '接口名称不可为空',
                    },{
                      validator: '',
                    }],
                    initialValue: this.state.name
                  })(


                    <Input placeholder="请输入接口名称"   />

                  )}
                </Form.Item>
                <Form.Item
                  label={<FormattedMessage id="app.customApi.requestMethod" />}
                  hasFeedback
                >
                  {getFieldDecorator('method', {
                    rules: [{
                      required: true, message: '请选择接口请求方式',
                    },{
                      validator: '',
                    }],
                    initialValue:  this.state.method
                  })(
                    <Select >
                      <Option value="GET">GET</Option>
                      <Option value="POST">POST</Option>
                    </Select>
                  )}

                </Form.Item>
                <Form.Item
                  label={<FormattedMessage id="app.customApi.requestAddress" />}
                  hasFeedback
                >
                  {getFieldDecorator('url', {
                    rules: [{
                      required: true, message: '请输入请求地址不可为空',
                    },{
                      validator: this.checkUrl,
                    }],
                    initialValue:  this.state.url
                  })(
                    <Input placeholder="请输入请求地址，以HTTP开头"  />
                    )}
                </Form.Item>
                <Form.Item
                  label={<FormattedMessage id="app.customApi.requestField" />}
                >
                  {
                    <Button type="dashed" htmlType='button' icon='plus' style={{marginLeft:10,marginRight:5,backgroundColor:'skyblue',color:'#fff'}} onClick={()=>this.addField('requestField')}><FormattedMessage id="app.customApi.add" /></Button>

                  }
                </Form.Item>
                <Form.Item>
                  <FieldTable data={this.state.requestField} columns={this.requestFieldColumns} />
                </Form.Item>
                <Form.Item
                  label={<FormattedMessage id="app.customApi.responseField" />}
                >
                  {
                <Button type="dashed"  htmlType='button' icon='plus' style={{marginLeft:10,marginRight:5,backgroundColor:'orange',color:'#fff'}} onClick={()=>this.addField('responseField')}><FormattedMessage id="app.customApi.add" /></Button>
                  }
                </Form.Item>
                <Form.Item>
                  <FieldTable  data={this.state.responseField} columns={this.responseFieldColumns} />
                </Form.Item>
                <Form.Item
                  label={<FormattedMessage id="app.customApi.Call-Failed-the-art-of-speaking" />}
                  hasFeedback
                >
                  {getFieldDecorator('errorMessage', {
                    rules: [{
                      required: true,message: '请输入调用失败话术'
                    },{
                      validator: "",
                    }],
                    initialValue:  this.state.errorMessage
                  })(
                   <Input placeholder="请输入调用失败话术"  />
                  )}

                </Form.Item>
                <Form.Item>
                  <Button htmlType='button' style={{marginLeft:143}} onClick={()=>{this.testApi(this.state.fieldObj)}}><FormattedMessage id="app.customApi.apiTest" /></Button>
                  {
                    <Button type='primary' htmlType='submit' style={{marginLeft:10}}><FormattedMessage id="app.customApi.apiSave"  /></Button>

                  }
                </Form.Item>
              </Form>
              <EditModal wrappedComponentRef={e => this.EditModal = e} addRequestFieldFun = {this.pushRequestField} />
            </Card>
        </Suspense>
      );
    }
}

export default connect (({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(CustomApi));
